package cn.colins.raft.rpc.handler.chanel;


import cn.colins.raft.enity.HeartBeatRequest;
import cn.colins.raft.enity.HeartBeatResult;
import cn.colins.raft.config.ServerConfig;
import cn.colins.raft.enity.RaftNodeInfo;
import cn.colins.raft.enums.NodeStatusEnums;
import cn.colins.raft.node.RaftNodeService;
import cn.colins.raft.rpc.domin.RpcRemoteMsg;
import cn.colins.raft.rpc.session.RpcSessionFactory;
import cn.colins.raft.state.StateMachines;
import cn.colins.raft.utils.ThreadPoolUtils;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Description  投票请求处理类
 * @Author czl
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2023/6/12
 */
public class HeartBeatHandler extends SimpleChannelInboundHandler<HeartBeatRequest> {
    private static final Logger log = LoggerFactory.getLogger(HeartBeatHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext context) throws Exception {
        Channel channel = context.channel();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext context, HeartBeatRequest rpcResponse) throws Exception {

        // 心跳请求处理
        RaftNodeService.heartBeatHandler(rpcResponse,context.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("[{}] 发生异常下线：{}",ctx.channel().remoteAddress(),cause.getMessage(),cause);
        // 需要移除通信管道
        String address = ctx.channel().remoteAddress().toString().replace("/", "");
        String[] split = address.split(":");
        ServerConfig serverConfig = new ServerConfig(split[0], Integer.valueOf(split[1]));
        RpcSessionFactory.channelClear(serverConfig);
        // 所以当前节点要是follow ，断开连接的又是当前leader 所以必须立刻发起投票
        if(NodeStatusEnums.FOLLOW.equals(RaftNodeInfo.getInstance().getCurrentNodeStatus())
                && serverConfig.toString().equals(RaftNodeInfo.getInstance().getCurrentLeader())){
            log.debug("leader 宕机了，我必须立刻发起投票");
            // 状态变更
            StateMachines.becomeCandidate();
            // 销毁现在的心跳检测
            RaftNodeService.electionTaskDestroy();
            // 发起投票
            RaftNodeService.sendCallVote();
        }

    }
}
